<template>
	<view class="page">
		<navbar title="蜂竞技-词源挑战" :close-confirm="true" @leaveRoom="fnLeaveRoom" />
		<view class="top-hr" style="height: 0px;"></view>

		<!-- <uv-modal ref="modal" title="温馨提示" @confirm="confirmCreate" :showCancelButton="true">
			<view class="slot-content">
				<rich-text :nodes="content"></rich-text>
			</view>
		</uv-modal> -->
		<uv-notify ref="uNotify" message="Hi uView" type="success"></uv-notify>
		<view class="main" :style="{ height: scrollHeight + 'px',justifyContent:pipeiStatus==true?'center':''}">
			<view class="operate">
				<!-- <view class="rank-icon" @click="showTips = true">
					<image class="img" src="/static/image/game-icon1.png"></image>
				</view> -->
				<!-- 没连蓝牙加class：rank-icon-null，连上蓝牙后去掉 -->
				<!-- 			<view class="rank-icon rank-icon-null">
					<image class="img" src="/static/image/game-icon3.png"></image>
				</view>
				<view class="rank-icon rank-icon-null">
					<image class="img" src="/static/image/game-icon2.png"></image>
				</view> -->
			</view>
			<view class="level_item level_1">
				<view style="display: flex;flex-direction: column;align-items: center;overflow: hidden;">
					<view class="" style="">
						<image mode="aspectFit" style="width: 106px;overflow: hidden;margin-bottom: 10px;"
							src="/static/image/app/icon-cytz.png"></image>
					</view>
					<view class="" style="flex: 1;white-space: nowrap;overflow: hidden;">
						<!-- <titleBar title="| 极速拼词 |" :titlefs="28" remark="Speed Spell"></titleBar> -->
						<view class="title111">| 词源挑战 |</view>
						<view class="title222">Origins Challenge</view>
					</view>
					<view class="range">
						词库范围：小学组
					</view>
				</view>
			</view>

			<view class="level_item level_2" style="height:226px;">
				<view class="">
					<titleBar title="| 匹配模式 |" :titlefs="22"></titleBar>
				</view>
				<!-- 选择人数 -->
				<view style="display:flex;flex-direction: column;margin: 10px 0px;">
					<view class="">
						最大人数：{{game_info.max_people_num}}
					</view>
				</view>
				<view class="">
					<view class="" @click="pipeiStatus=true"
						style="width: 83%;margin: 0 auto;padding-top:30px;padding-bottom:10px;text-align: center;">
						正在匹配合适的对手...
					</view>
					<view class="pipei_room_btn_ing" @click="fnQuitPipei()" style="width: 83%;">
						取消匹配
						<view class="btn-en">Cancel Matching</view>
					</view>
				</view>
			</view>
		</view>

		<popRules v-if="showTips" :msg="rules" title="极速拼词游戏规则" @close="showTips = false" @confirm="showTips = false">
		</popRules>
	</view>
</template>

<script>
	import titleBar from '../../../components/games/title-bar.vue'
	import navbar from '../../../components/gamesNav.vue'
	import mifeng from '../../../components/games/mifeng.vue'
	import popRules from '../../../components/popRules.vue'
	export default {
		config: {
			disableScroll: true
		},
		onBackPress(options) {
			var that = this;
			// 点击虚拟键或者侧滑的时候触发（不允许返回）
			if (options.from === 'backbutton') {
				that.fnQuitPipei()
				return true
			}
			// 否则则允许返回
			return false;
		},
		components: {
			titleBar,
			navbar,
			mifeng,
			popRules
		},
		onShow() {
			const that = this
			that.$eventBus.$emit('callMethodIn_background_type', {
				type: 'menu'
			})
		},
		data() {
			return {
				game_mode: '',
				dev: true,

				// socket
				isSuccess: false,
				allReadyStatus: false, //所有人的准备状态
				isClose: false, //如何为true则不需要进行重连
				wsStatus: true, //websocket状态
				downtime_30: 0,
				pipei_success: 0, //1说明匹配成功

				user_info: {},
				game_info: {
					game_id: 10001, //极速拼词
					max_people_num: 6, //最大房间人数
				},
				show: false,
				title: '标题',
				content: '',

				people_num: 2, //房间人数
				showRoomBox: false,
				keyword: '',

				word: 'apple',
				scrollHeight: 0,
				gameWidth: 0,

				background: ['color1', 'color2', 'color3'],
				indicatorDots: true,
				autoplay: false,
				interval: 2000,
				duration: 500,

				room_list: [1, 2],
				showPromptbox: false,
				msg: '',
				showTips: false,

				pipeiStatus: true, //是否在匹配

				rules: `每位选手从词库中抽取45个单词在120s内进行速拼比赛。在发音官给出第一个单词发音后允许答题并开始计时，选手可以使用虚拟键盘或外接蓝牙键盘进行答题。
						输入单词完毕，点击键盘下方的提交按钮提交单词，由系统判断正误。
						选手可以点击屏幕“word”或对麦克风说“word”让发音官重新发音。
						选手可以点击“PASS”跳过该题，完成全部单词后回到第一个跳过的单词继续答题，直到完成全部单词。
						系统根据选手拼对单词数量排名，第一名可以获得等于房间人数的积分奖励，第二名为第一名的积分-1，依此类推。
						拼对单词数量为0的选手不计入房间总人数且不获得积分。
						若多人答对单词一致，则根据答对单词的难度进行排名，单词难度根据词频，单词长度，音标长度等进行划分。`,

				pipei_group_info: {},
				pipei_room_object: {
					100: {
						id: 100,
						groupname: '候车大厅：拼词竞技',
						grade: 1,
						people_num: 6,
						game_id: 10000
					},
					101: {
						id: 101,
						groupname: '候车大厅：小学组-极速拼词',
						grade: 1,
						people_num: 6,
						game_id: 10001
					},
					102: {
						id: 102,
						groupname: '候车大厅：初中组-极速拼词',
						grade: 1,
						people_num: 6,
						game_id: 10001
					},
					103: {
						id: 103,
						groupname: '候车大厅：高中组-极速拼词',
						grade: 1,
						people_num: 6,
						game_id: 10001
					}
				},
			};
		},
		onReady() {
			const that = this
			uni.createSelectorQuery().select('.top-hr').boundingClientRect(rect => {
				that.scrollHeight = uni.getSystemInfoSync().windowHeight - rect.bottom;
			}).exec();
		},
		mounted() {
			const that = this

			that.pipei_group_info = that.pipei_room_object['100'];
			console.log(that.pipei_group_info);
			// 连接socket
			that.connectSocket()

			that.$eventBus.$emit('callMethodIn_background_type', {
				type: 'menu'
			})
		},
		onLoad(options) {
			var that = this;
			that.user_info = JSON.parse(uni.getStorageSync('USER_INFO'));
			that.game_info = JSON.parse(decodeURIComponent(options.game_info));
			that.game_mode = options.game_mode;
			that.getGameConfigInfo();
		},
		beforeDestroy() {
			var that = this;
			console.log('beforeDestroy')
			that.isClose = true;
			if (that.socketTask) {
				that.socketTask.close();
			}
		},
		methods: {

			//连接websocket
			connectSocket() {
				let that = this;
				console.log('调用连接websocket')
				let token = uni.getStorageSync('TOKEN_YX');
				if (!that.user_info.id || !token) {
					that.fnNotify('参数异常');
					return false;
				}

				this.socketTask = uni.connectSocket({
					url: `ws://${that.$config.webSocketIp}:9999?token=${token}&user_id=${that.user_info.id}&group_id=${that.pipei_group_info.id}`,
					success(res) {
						console.log("websocket连接成功");
					},
					fail(err) {
						console.log("报错", err);
					}
				});
				this.socketTask.onOpen(function(res) {
					console.log('WebSocket连接已打开！');
					that.isSuccess = true
					// that.getStatus()
					that.heart()

					//发送消息
					setTimeout(function() {
						var content = '进入候车大厅';
						content = "#" + content + "#-" + that.user_info.id;
						that.fnSendMessage(content);
					}, 500)
				})

				this.socketTask.onMessage(function(res) {
					console.log('收到候车大厅：服务器内容：' + res.data);
					that.handlerServiceMsg(JSON.parse(res.data)) //这里是对获取到的数据进行操作
				});


				this.socketTask.onError(function(res) {
					if (that.pipei_success == 1) {
						return false;
					}
					console.log('WebSocket连接打开失败，请检查！');
					// that.fnNotify('WebSocket连接打开失败，请检查！');
					that.wsStatus = false;
					console.log(res);
					// this.isSuccess = false
					// that.connectSocket()

					//进入重新连接
					that.reconnect();
				})
				// // 监听连接关闭 -
				this.socketTask.onClose((e) => {
					console.log('WebSocket连接关闭！');
					clearInterval(that.timer)
					that.timer = ''

					that.reconnect()

				})
				console.log(this.socketTask)
			},
			getGameConfigInfo() {
				var that = this;
				that.$http.getGameConfigInfo({
					'game_id': that.game_info.id,
					'game_mode': that.game_mode
				}).then(res => {
					if (res.code === 200) {
						that.game_info = res.data;
					}
				})
			},
			//进入重新连接
			reconnect() {
				var that = this;
				if (that.isClose == true) {
					return false;
				}
				console.log('进入断线重连');
				// this.socketTask.close();
				this.socketTask = null;
				this.connectSocket()
			},

			//发送消息
			sendSocketMessage(msg) {
				// console.log('发送信息')
				// console.log(msg)
				return new Promise((reslove, reject) => {
					this.socketTask.send({
						data: msg,
						success(res) {
							// console.log('发送成功')
							reslove(res)
						},
						fail(res) {
							console.log('发送失败')
							console.log(res)
							reject(res)
						}
					});
				})
			},

			//心跳
			heart() {
				let that = this;
				clearInterval(this.timer);
				this.timer = '';
				let msg = {
					"type": "heartbeat",
				}
				this.timer = setInterval(() => {
					that.sendSocketMessage(JSON.stringify(msg)).then(res => {
						// console.log('心跳成功')
					}).catch(res => {
						console.log('发送失败')
						console.log((res))
					})
				}, 5000)
			},

			//处理服务器返回数据
			handlerServiceMsg(data) {
				var that = this;

				if (data.type && data.type == 'ping') {
					return false;
				}
				var content = data.content;

				console.log('################处理服务器返回数据:data-----', data, content)

				// 更新数据
				if (data._total_user_info) {
					that.user_list = data._total_user_info;
				}


				// 进入房间
				if (content.includes('进入候车大厅')) {

					var enterer_userId = content.split('-')[1];
					console.log('################data', data)
					if (enterer_userId == that.user_info.id) {
						console.log('是本人！！！！！！！！！！！！！！！！！！', enterer_userId)
						// 开始答题后：统计答题正确率
					} else {
						that.fnNotify('有人进入候车大厅');
					}
				}

				// 30秒倒计时， 游戏开始
				if (content.includes('30秒匹配倒计时')) {
					that.downtime_30 = 10 - data._downtime30;
					console.log(that.downtime_30)

					// that.fnNotify(content);
					if (that.downtime_30 == 0) {
						that.pipei_success = 1;
						that.fnNotify('匹配成功，即将进入游戏房间');
					} else {
						that.fnNotify(that.downtime_30 + '秒后，即将进入游戏房间' + '【' + that.user_list.length + '】');
					}
				}

				// 匹配成功，创建游戏房间并进入
				if (content.includes('匹配成功，创建游戏房间并进入')) {
					// 清除心跳定时器
					if (that.timer) {
						clearInterval(that.timer);
						that.timer = '';
					}

					that.isClose = true;
					that.socketTask.close();

					setTimeout(function() {
						that.fnEnterRoom(data._group_info, 0);
					}, 500)
				}

				// 离开房间
				if (content.includes('离开候车大厅')) {
					that.fnNotify('有人离开候车大厅');
				}
			},

			fnSendMessage(content) {
				var that = this;

				content = that.game_mode + content;
				console.log('发送消息：' + content)

				//发送消息
				var message = {
					'type': 'chatMessage',
					'data': {
						"mine": {
							"username": that.user_info.username,
							"avatar": that.user_info.avatar,
							"id": that.user_info.id,
							"mine": true,
							"type": "group",
							"content": content
						},
						"to": {
							"id": that.pipei_group_info.id,
							"user_id": that.user_info.id,
							"avatar": that.pipei_group_info.avatar,
							"sign": that.pipei_group_info.sign,
							"groupname": that.pipei_group_info.groupname,
							"name": that.pipei_group_info.groupname,
							"type": "group"
						}
					}
				};
				that.sendSocketMessage(JSON.stringify(message)).then(res => {
					console.log('测试数据成功~~~~~~~~~~~~')
				}).catch(res => {
					console.log('发送失败')
					console.log((res))
				})
			},

			// 消息提示
			fnNotify(msg) {
				var that = this;
				msg = that.game_mode + msg;

				if (that.dev_btn_show == false) {
					return false;
				}
				that.$refs.uNotify.close()
				setTimeout(function() {
					that.$refs.uNotify.show({
						top: 50,
						type: 'error',
						color: '#000',
						bgColor: '#e8e8e8',
						message: msg,
						duration: 1000 * 3,
						fontSize: 20,
						safeAreaInsetTop: true
					})
				}, 100)
			},

			fnPipei() {
				var that = this;
				that.pipeiStatus = true;

				that.pipei_group_info = that.pipei_room_object['101'];
				console.log(that.pipei_group_info);
				setTimeout(function() {
					// 连接socket
					that.connectSocket()
					// that.getPipeiRoomList();
				}, 1000)
			},

			fnQuitPipei() {
				var that = this;
				var keyword = '离开候车大厅';

				// 离开候车大厅
				var content = "#" + keyword + "#";
				that.fnNotify("#" + keyword + "#");
				// 发送消息
				that.fnSendMessage(content);

				// 清除心跳定时器
				if (that.timer) {
					clearInterval(that.timer);
					that.timer = '';
				}

				that.isClose = true;
				that.socketTask.close();

				setTimeout(function() {
					uni.navigateBack();
				}, 500)
			},

			// 获取房间列表
			getPipeiRoomList() {
				var that = this;
				that.$http.getPipeiRoomList({
					'people_num': that.people_num
				}).then(res => {
					that.pipeiStatus = false;
					console.log('1*******1')
					console.log(res)
					if (res.code === 200) {
						that.room_list = res.data
						if (that.room_list.length > 0) {
							var item = that.room_list[that.room_list.length - 1];
							var index = that.room_list.length - 1;
							that.fnEnterRoom(item, index);
						} else {
							uni.showToast({
								title: '未匹配到房间，请稍后再试~',
								icon: 'none',
								duration: 2000
							})
						}
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none',
							duration: 2000
						})
					}
				})
			},

			fnSearch() {
				var that = this;

				that.getRoomList();
			},


			// 获取房间列表
			getRoomList() {
				var that = this;
				that.$http.getRoomList({
					keyword: that.keyword
				}).then(res => {
					console.log('1*******1')
					console.log(res)
					if (res.code === 200) {
						that.room_list = res.data
						if (that.room_list.length == 0) {
							uni.showToast({
								title: '暂无房间数据',
								icon: 'none',
								duration: 2000
							})
						}
					} else {
						uni.showToast({
							title: res.msg,
							icon: '',
							duration: 2000
						})
					}
				})
			},

			// 离开房间：
			// 开始前：如果是选手离开，则相当于退出房间，如果是群主离开房间，相当于是解散房间
			// 开始后：离开相当于离线，不退出
			fnLeaveRoom() {
				var that = this;

				that.fnQuitPipei();
			},

			// 进入房间
			fnEnterRoom(group_info, index) {
				var that = this;

				const params = {
					group_id: group_info.id,
				}
				that.$http.checkBeforeEnterRoom(params).then(res => {
					if (res.code === 200) {
						// var group_info = {
						// 	"id": item.id,
						// 	"user_id": item.user_id, //房主
						// 	"avatar": item.avatar ? item.avatar : "http://chat.soullions.com/avatar.jpg",
						// 	"sign": item.sign,
						// 	"groupname": item.groupname,
						// };

						uni.redirectTo({
							url: '/pages/games/pcjj/game_pcjj' +
								'?group_info=' + encodeURIComponent(JSON.stringify(group_info)) +
								'&game_mode=' + that.game_mode +
								'&game_info=' + encodeURIComponent(JSON.stringify(that.game_info))
						})
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none',
							duration: 2000
						})
					}
				})
			},

			// 关闭弹框
			close() {
				var that = this;
				that.show = false;
			},

			handleToGame() {
				uni.navigateTo({
					url: '/pages/game_round_1/game'
				})
			},

			changeIndicatorDots(e) {
				this.indicatorDots = !this.indicatorDots
			},
			changeAutoplay(e) {
				this.autoplay = !this.autoplay
			},
			intervalChange(e) {
				this.interval = e.target.value
			},
			durationChange(e) {
				this.duration = e.target.value
			}
		}
	}
</script>

<style lang="scss">
	.page {
		background-image: url(/static/image/app/gameBg.png);
		// background-color: #f7b52c;
		background-size: 100% auto;
		background-position: top left;
		background-repeat: no-repeat;
		width: 100%;
		height: 100vh;
		background-size: 100% 100%;
		text-align: center;
		font-family: hzgb;
	}

	.main {
		// border: 2px solid blue;
		width: 100%;
		height: 100vh;
		display: flex;
		flex-direction: column;
		overflow-y: auto;
		position: relative;

		.level_item {
			// overflow: hidden;
		}
	}

	.level_1 {
		display: flex;
		align-items: center;
		justify-content: center;
		margin-top: 20px;
	}

	.level_2 {
		min-height: 168px;
		margin: 20px;
		margin-bottom: 0px;
		border-radius: 20px;
		color: white;
		background-image: linear-gradient(to bottom, rgba(128, 128, 128, 0.33), rgba(128, 128, 128, 0.17));
		padding-top: 25px;

		.pipei_room_btn {
			width: 200px;
			color: black;
			margin: 0 auto;
			background: yellow;
			border-radius: 12px;
			height: 50px;
			line-height: 50px;
			background: linear-gradient(to bottom, #ffd16b, #fff497);
			box-shadow: 0px 7px 0px 0px rgba(209, 165, 77, 1);
			margin: 16px auto 0;
		}

		.pipei_room_btn_ing {
			width: 200px;
			color: white;
			margin: 20px auto 0;
			background: yellow;
			border-radius: 12px;
			height: 50px;
			// line-height: 50px;
			padding-top: 10px;
			background: linear-gradient(to bottom, #ff2b1d, #ff2b1d);
			box-shadow: 0px 7px 0px 0px rgba(184, 28, 37, 1);
			margin: 0 auto;
		}

		.create_room_btn {
			width: 200px;
			color: black;
			margin: 0 auto;
			background: yellow;
			border-radius: 12px;
			height: 50px;
			line-height: 50px;
			background: linear-gradient(to bottom, #ffd16b, #fff497);
			box-shadow: 0px 7px 0px 0px rgba(209, 165, 77, 1);
			margin: 0 auto;
		}

		.show_room_btn {
			width: 120px;
			margin: 20px auto;
			border-radius: 21px;
			background-position: center center;
			background-size: 100% 100%;
			height: 40px;
			line-height: 40px;
			color: black;
			background: linear-gradient(to bottom, #ffd16b, #fff497);
			box-shadow: 0px 6px 0px 0px #d1a54d;
		}

		.room_box {
			display: flex;
			flex-direction: column;

			height: auto;
			margin: 20px;

			.room_search {
				display: flex;
				flex-direction: row;
				background: #fff8e1;
				border-radius: 20px;
				height: 32px;
				line-height: 32px;
				justify-content: center;
				align-items: center;
				padding: 0px 3px;
				font-family: normal;
				margin-bottom: 10px;

				.search_left {
					width: 50px;
					background-image: url("/static/image/app/fangdajing.png");
					height: 50px;
					background-size: 22px;
					background-repeat: no-repeat;
					background-position: center center;
				}

				.search_center {
					flex: 1;
				}

				.search_right {
					width: 60px;
					background: black;
					border-radius: 20px;
					height: 26px;
					line-height: 26px;
					font-size: 14px;
				}
			}
		}
	}

	.level_3 {
		flex: 1;
		margin: 20px;
		margin-bottom: 20px;
		border-radius: 20px;
		color: white;
		background-image: linear-gradient(to bottom, rgba(128, 128, 128, 0.33), rgba(128, 128, 128, 0.17));
		padding-top: 25px;

		.create_room_btn {
			width: 200px;
			color: black;
			font-weight: bold;
			margin: 0 auto;
			background: yellow;
			border-radius: 12px;
			height: 50px;
			line-height: 50px;
			background: linear-gradient(to bottom, #ffd16b, #fff497);
			box-shadow: 0px 7px 0px 0px rgba(209, 165, 77, 1);
			margin: 0 auto;
		}

		.show_room_btn {
			width: 120px;
			margin: 20px auto;
			border-radius: 21px;
			background-position: center center;
			background-size: 100% 100%;
			height: 40px;
			line-height: 40px;
			color: black;
			background: linear-gradient(to bottom, #ffd16b, #fff497);
			box-shadow: 0px 6px 0px 0px #d1a54d;
		}

		.room_box {
			display: flex;
			flex-direction: column;

			height: auto;
			margin: 20px;

			.room_search {
				display: flex;
				flex-direction: row;
				background: #fff8e1;
				border-radius: 20px;
				height: 32px;
				line-height: 32px;
				justify-content: center;
				align-items: center;
				padding: 0px 3px;
				font-family: normal;
				margin-bottom: 10px;

				.search_left {
					width: 50px;
					background-image: url(/static/image/app/fangdajing.png);
					height: 50px;
					background-size: 22px;
					background-repeat: no-repeat;
					background-position: center center;
				}

				.search_center {
					flex: 1;
				}

				.search_right {
					width: 60px;
					background: black;
					border-radius: 20px;
					height: 26px;
					line-height: 26px;
					font-size: 14px;
				}
			}
		}
	}



	.range {
		color: #fff;
		margin-top: 18px;
		font-size: 18px;
	}

	// 创建房间页面，选择人数的滑块样式
	::v-deep .uni-slider-handle-wrapper {
		height: 14px !important;
		border-radius: 14px !important;
	}

	::v-deep .uni-slider-track {
		border-top-left-radius: 14px;
		border-bottom-left-radius: 14px;
	}

	.operate {
		position: absolute;
		top: 10px;
		right: 12px;
		width: 30px;

		.rank-icon {
			width: 30px;
			height: 30px;
			border-radius: 4px;
			background: linear-gradient(to top, #fff497, #ffd16b);
			box-shadow: 0 4px 0 0 #d9b059;
			margin-bottom: 12px;

			.img {
				width: 30px;
				height: 30px;
			}
		}

		.rank-icon-null {
			background: linear-gradient(to top, #cfcfcf, #a1a1a1);
			box-shadow: 0 4px 0 0 #969696;
		}
	}

	.title111 {
		color: #fff;
		font-size: 24px;
		margin-bottom: 4px;
	}

	.title222 {
		color: #fff;
		font-size: 14px;
	}
</style>